const Service = require("egg").Service;
const { list_to_tree, get_all_folder_id } = require("../utils/tools");

class MenuService extends Service {
  // 菜单信息
  async info_by_menu_name(menu_name) {
    const result = await this.app.mysql.get("menu", {
      menu_name,
    });
    return result;
  }

  // 新增菜单
  async add({ pid, menu_name, code, type = "route" }) {
    const menu = await this.app.mysql.get("menu", {
      menu_name,
    });
    const tem = {};
    if (menu) {
      tem.type = "fail";
      tem.message = "该菜单已经存在!";
    } else {
      const result = await this.app.mysql.insert("menu", {
        pid,
        menu_name,
        code,
        type,
        create_time: Date.now(),
        update_time: Date.now(),
      });
      tem.type = "success";
      tem.message = "新增成功";
    }

    return tem;
  }

  // 修改菜单
  async edit({ id, menu_name, code, type }) {
    const result = await this.app.mysql.update("menu", {
      id,
      menu_name,
      code,
      type,
      update_time: Date.now(),
    });
    return result;
  }

  // 查询菜单
  async list() {
    const data = await this.app.mysql.select("menu");
    const total = await this.app.mysql.count("menu");
    return {
      data: list_to_tree(data),
      total,
    };
  }

  // 删除菜单
  async delete(id) {
    const data = await this.app.mysql.select("menu");
    const ids = get_all_folder_id(data, id)
      .map((item) => item.id)
      .join();
    const all_cid = `(${ids && ids + ","}${id})`;
    const result = await this.app.mysql.query(
      `delete from menu where id in ${all_cid};`
    );
    return result;
  }
}

module.exports = MenuService;
